<template>
  <div class="search-container">
    <h1 class="search-title">请输入水产品名称或图片</h1>

    <!-- 搜索区域 -->
    <div class="search-box">
      <div class="search-input-group">
        <input 
          type="text" 
          placeholder="输入关键字"
          class="search-input"
          v-model="searchQuery"
          @keyup.enter="debouncedSearch"
        />

        <!-- 图片上传按钮 -->
        <input 
          type="file" 
          ref="fileInput" 
          accept="image/*" 
          @change="handleImageUpload" 
          style="display: none;"
        />
        <button class="icon-btn image-upload-btn" @click="triggerUpload" :disabled="loading">
          <svg viewBox="0 0 24 24">
            <path d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
          </svg>
        </button>
        <!-- 搜索按钮 -->
        <button class="search-btn" @click="handleSearch" :disabled="loading">
          <svg v-if="loading" viewBox="0 0 24 24">
            <path d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
          <svg v-else viewBox="0 0 24 24">
            <path d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          {{ loading ? '搜索中...' : '搜索' }}
        </button>
      </div>

      <!-- 图片预览缩略图 -->
      <div class="image-preview" v-if="previewUrl" @click="triggerUpload">
        <img :src="previewUrl" alt="预览图" />
      </div>

      <!-- 快捷搜索 -->
      <div class="quick-search">
        <span class="quick-search-label">快捷搜索：</span>
        <button 
          v-for="(item, index) in quickSearchItems" 
          :key="index"
          @click="quickSearch(item)"
          class="quick-search-item"
        >
          {{ item }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { fishRecognitionApi } from '@/api/fishRecognition';
import { emitter } from '@/utils/emitter';
import { ElMessage } from 'element-plus';

const searchQuery = ref('');
const fileInput = ref(null);
const previewUrl = ref('');
const quickSearchItems = ['远海梭子蟹', '宽尾斜齿鲨', '华贵栉孔扇贝', '方斑东风螺', '鲻'];
// 添加selectedFile引用以存储选中的文件
const selectedFile = ref(null);
// 添加loading状态
const loading = ref(false);

const triggerUpload = () => {
  // 如果搜索框有文字，则不能进行图片搜索
  if (searchQuery.value.trim()) {
    ElMessage.warning('请先清除搜索框中的文字再进行图片搜索');
    return;
  }
  fileInput.value?.click();
}

const handleImageUpload = (event) => {
  const file = event.target.files[0];
  if (file && file.type.startsWith('image/')) {
    selectedFile.value = file; // 保存选中的文件
    const reader = new FileReader();
    reader.onload = () => {
      previewUrl.value = reader.result;
      // 只有当没有输入文字时才自动触发图片搜索
      if (!searchQuery.value.trim()) {
        handleSearch();
      }
    };
    reader.readAsDataURL(file);
  }
}

// 防抖函数
const debounce = (fn, delay) => {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
};

// 文字搜索处理
const handleTextSearch = () => {
  if (loading.value || !searchQuery.value.trim()) return;
  
  const list = [{
    name:'中华单角鲀',
    englishName:'Monacanthus chinensis',
    path:'/src/assets/yutu/sea-cucumber/cucumber2.jpg'
  },{
    name:'宽尾斜齿鲨',
    englishName:'Scoliodon laticaudus',
    path:'/src/assets/yutu/fish/fish2.jpeg'
  },{
    name:'远海梭子蟹',
    englishName:'Portunus pelagicus',
    path:'/src/assets/yutu/crab/crab2.jpeg'
  },{
    name:'鲻',
    englishName:'Mugil cephalus',
    path:'/src/assets/yutu/fish/fish1.jpeg'
  },{
    name:'栉江瑶',
    englishName:'Atrina pectinata',
    path:'/src/assets/yutu/shellfish/shell1.jpeg'
  },{
    name:'华贵栉孔扇贝',
    englishName:'Mimacalamys nobilis',
    path:'/src/assets/yutu/shellfish/shell2.jpeg'
  },{
    name:'皱纹盘鲍',
    englishName:'Haliotis discus hannai',
    path:'/src/assets/yutu/shellfish/shell3.jpeg'
  },{
    name:'凡纳滨对虾',
    englishName:'Litopenaeus vannamei',
    path:'/src/assets/yutu/shrimp/shrimp1.jpeg'
  },{
    name:'斑节对虾',
    englishName:'Penaeus monodon',
    path:'/src/assets/yutu/shrimp/shrimp2.jpeg'
  },{
    name:'方斑东风螺',
    englishName:'Babylonia areolata',
    path:'/src/assets/yutu/snail/snail1.jpeg'
  }]

  // 定义一个函数来检查鱼类名称是否匹配
  function isFishMatch(fish) {
    // fish 是数组中的当前元素
    // fish.name 是当前鱼类的名称
    // searchQuery.value 是用户输入的内容
    // 这个函数返回 true 表示匹配，false 表示不匹配
    return fish.name === searchQuery.value;
  }

  // 使用 find 方法查找匹配的鱼类
  // find 方法会遍历 list 数组，对每个元素调用 isFishMatch 函数
  // 如果 isFishMatch 返回 true，find 就会返回这个元素
  // 如果遍历完所有元素都没有找到匹配的，find 就会返回 undefined
  const matchedFish = list.find(isFishMatch);
  
  if (matchedFish) {
    // 发送匹配到的图片路径
    emitter.emit('update-fish-image', matchedFish.path);
    // 发送中文名和英文名
    emitter.emit('update-fish-chinese-name', matchedFish.name);
    emitter.emit('update-fish-english-name', matchedFish.englishName);
    emitter.emit('update-fish-confidence', '待识别');
  } else {
    // 如果没有匹配项，显示错误提示
    ElMessage.error('未搜索到内容');
  }
};

// 图片搜索处理
const handleImageSearch = async () => {
  if (loading.value || !previewUrl.value || !selectedFile.value) return;
  
  loading.value = true;
  try {
    const formData = new FormData();
    formData.append('image', selectedFile.value);
    
    const uploadResponse = await fishRecognitionApi.uploadImage(formData);
    console.log('图片上传结果:', uploadResponse);
    
    // 无需再发送图片事件
    loading.value = false;
  } catch (error) {
    console.error('图片识别失败:', error);
    // 移除alert，依赖request.js中的ElMessage错误提示
    loading.value = false;
  }
};

// 防抖处理的搜索方法
const debouncedSearch = debounce(handleTextSearch, 300);

// 修改原始handleSearch方法
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    handleTextSearch();
  } else if (previewUrl.value && selectedFile.value) {
    handleImageSearch();
  } else {
    console.log('请输入关键词或上传图片');
  }
};

const quickSearch = (item) => {
  searchQuery.value = item;
  handleSearch();
};
</script>

<style scoped>
.search-container {
  padding: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 200px;
  box-sizing: border-box;
}

.search-title {
  color: white;
  font-size: 1.1rem;
  margin-bottom: 8px;
  text-align: center;
}

.search-box {
  width: 100%;
  background-color: rgba(0, 0, 0, 0.3); 
  /* 改为半透明黑色 */
  border-radius: 12px; /* 增加圆角 */
  padding: 10px 16px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3); /* 增强阴影提升层次感 */
  box-sizing: border-box;
  position: relative;
}

.search-input-group {
  display: flex;
  align-items: center;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  font-size: 0.95rem;
  border: none;
  outline: none;
  color: #ffffff; /* 白色字体提升可读性 */
  background-color: rgba(255, 255, 255, 0.1); /* 输入框背景也做轻微透明处理 */
  border-radius: 6px; /* 圆角与容器风格统一 */
}

.search-input::placeholder {
  color: #a0aec0;
}

.icon-btn {
  background: none;
  border: none;
  padding: 4px;
  cursor: pointer;
}

.icon-btn svg {
  width: 20px;
  height: 20px;
  stroke: #718096;
  fill: none;
  stroke-width: 2;
}

.icon-btn:hover svg {
  stroke: #3182ce;
}

.search-btn {
  background-color: #3182ce;
  color: white;
  padding: 6px 12px;
  font-size: 0.85rem;
  border-radius: 4px;
  margin-left: 8px;
  display: flex;
  align-items: center;
  transition: background-color 0.2s;
}

.search-btn:hover {
  background-color: #2c5282;
}

.search-btn svg {
  width: 18px;
  height: 18px;
  margin-right: 4px;
  stroke: currentColor;
  fill: none;
  stroke-width: 2;
}

.image-preview {
  position: absolute;
  top: -40px;
  right: 12px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #fff;
  box-shadow: 0 0 0 2px #3182ce;
  cursor: pointer;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.quick-search {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  font-size: 0.85rem;
}

.quick-search-label {
  color: #4fd1c5;
  opacity: 0.7;
  margin-right: 8px;
}

.quick-search-item {
  margin: 2px 6px;
  padding: 2px 10px;
  border-radius: 9999px;
  background-color: #2a4365;
  color: white;
  cursor: pointer;
  transition: background-color 0.2s;
}

.quick-search-item:hover {
  background-color: #2c5282;
}
</style>